<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once ( LIB_DIR.'search/shopsearch.php' );
require_once ( LIB_DIR.'classes/Pager.php' );
require_once ( LIB_DIR.'model/ProductCategoryDAO.php' );
require_once ( LIB_DIR.'model/ShopDAO.php' );

//declare global vars
global $cityList,$platformList, $cityMap;

$pageVars = array();

$pageVars['cityList'] = $cityList;
$pageVars[ "ismall" ] = false;
//TODO use memcache later
$shopcategory = GetShopCategoryDAO();
$allCategories = $shopcategory->GetLevel1Category();
$pageVars['shopcatelist'] = $allCategories;
$cateMapping=EdpGetAllShopCateMapping();

$validSortby = array( "score", "service", "reality", "velocity", "rate", "review_count" );

if( !isset( $_GET['q'] ) ) {
//do nothing, just display
}
else {
	$keyword = htmlspecialchars( $_GET['q'] );

	$sortby = "";
	if( !empty( $_GET['sortby'] ) )
		$sortby = $_GET['sortby'];
	else
		$sortby = "score-desc";
	$location = '';
	if( isset( $_GET['location'] ) )
		$location =$_GET['location'];
	$plat_id = '';
	if( isset( $_GET['platid'] ) )
		$plat_id = intval( $_GET['platid'] );
	$category = '';
	if( isset( $_GET['category'] ) )
		$category = htmlspecialchars( $_GET['category'] );
	$paymethod = '';
	if( isset($_GET['paymethod']) ){
		if( is_array( $_GET['paymethod'] ) && !empty($_GET['paymethod'][0]) )
			$paymethod = htmlspecialchars( $_GET['paymethod'] );
	}
	$feature = '';
	if( isset($_GET['feature']) ){
		if( is_array( $_GET['feature'] ) && !empty($_GET['feature'][0]) )
			$feature = htmlspecialchars( $_GET['feature'] );
	}
	$tag = '';
	if( isset($_GET['tag']) )
		$tag = $_GET['tag'];
	$page = 1;
	if( isset( $_GET['p'] ) ) {
		$page = intval( $_GET['p'] );
	}

	$shopSearch = new ShopSearch();
	//clean keyword
	$keyword = $shopSearch->CleanKeyword( $keyword );
	// move page var keyword forward
	$pageVars['keyword'] = $keyword;
	$searchType = NORMAL_QUERY;

	// test group by search
	//$result = $shopSearch->GroupByQuery( $keyword, 'plat_id' );

	//determine the search type
	$filterArray = array();
	$additionalKeyword = array();
	if( !empty( $location ) ) {
		$searchType = FILTER_QUERY;
		$locationids = explode( ",", $location );

		//set page var
		$pageVars['location'] = $location;

		//read sub cities from citymap
		$locationFullIds = $locationids;
		foreach( $locationids as $lid ){
			if( isset( $cityMap[$lid] ) ){
				$locationFullIds = array_merge( $cityMap[$lid]['cityids'], $locationFullIds );
			}
		}
		$filterArray['location'] = $locationFullIds;
	}
	if( !empty( $plat_id ) ) {
		$searchType = FILTER_QUERY;
		if( intval($plat_id) == 0)
			$filterArray['plat_id'] = "$plat_id,99";
		else if( intval($plat_id) == 100)
			$filterArray['plat_id'] = "$plat_id,1000";
		else
			$filterArray['plat_id'] = array( intval($plat_id) );

		$pageVars['plat_id'] = $plat_id;
	}
        //default search type is c2c
        else{
            $searchType = FILTER_QUERY;
            $filterArray['plat_id'] = "0,99";
        }

	if( !empty( $category ) ) {
		$searchType = FILTER_QUERY;
		$filterArray['cate_id_list'] = array( intval($category) );

		$pageVars['cate_id_list'] = $category;
	}
	else{
		$pageVars['cate_id_list'] = "";
	}
	if( !empty( $paymethod ) ) {
		$searchType = FILTER_QUERY;
		$strPaymethod = implode( "," , $paymethod);

		//add field specified query to $keyword parameter
		$additionalKeyword['@paymethod'] = $strPaymethod;

		$pageVars['paymethod'] = $strPaymethod;
	}
	if( !empty( $feature ) ) {
		$searchType = FILTER_QUERY;
		$strFeature = implode( "," , $feature);

		//add field specified query to $keyword parameter
		$additionalKeyword['@feature'] = $strFeature;

		$pageVars['feature'] = $strFeature;
	}
	if( !empty( $tag ) ) {
		$searchType = FILTER_QUERY;

		//add field specified query to $keyword parameter
		$additionalKeyword['@tag'] = $tag;

		$pageVars['tag'] = $tag;
	}
	$isDesc = true;
	if( !empty( $sortby ) ) {
		$pageVars['sortby'] = $sortby;

		//parse sort
		//price0 is sort by price asc and price1 is sortby price desc
		$sortbyArray = explode( "-", $sortby );
		if( count($sortbyArray) == 2 && in_array($sortbyArray[0], $validSortby) ){
			$sortby = $sortbyArray[0];
			$isDesc = $sortbyArray[1] == "asc"? false : true;
		}
		else {
			$sortby = "";
		}

		if( $sortby != "" ){
			if( $searchType == FILTER_QUERY ) {
				$searchType = FILTER_SORT_QUERY;
			}
			else {
				$searchType = SORT_QUERY;
			}
		}
	}

	//set plat id
	if( intval( $plat_id ) == 100 ){
		$pageVars[ "ismall" ] = true;
	}
	//assemble keyword
	foreach( $additionalKeyword as $key=>$value ) {
		$keyword .= " $key $value";
	}
	
	$result = array();
	switch( $searchType ) {
		case NORMAL_QUERY:
			$result = $shopSearch->Query( $keyword, $page );
			break;
		case SORT_QUERY:
			$result = $shopSearch->SortQuery( $keyword, $sortby, $page, $isDesc );
			break;
		case FILTER_QUERY:
			$result = $shopSearch->MultiFilterQuery( $keyword, $filterArray, $page );
			break;
		case FILTER_SORT_QUERY:
			$result = $shopSearch->MultiFilterAndSortQuery( $keyword, $filterArray, $sortby, $page, $isDesc );
			break;
	}

	$pageVars['result'] = $result;
	if( $result['total'] > 0 ) {
		//!!!!shit here, need to sort the result with extra sql statement : ORDER BY FIELD(id, ".$strIds.")
		//and then do sort here
		$shopDao = GetShopDAO();
		$dbRes = $shopDao->GetShopInfoByIdList( $result['matchIds'] );

		$highLighRes = array();
		foreach( $dbRes as $row ) {
			$row['shop_name_plain'] = $row['shop_name'];
			$row['tags_plain'] = $row['tags'];
			//assemble field to highlight : shopname, shop description, nick, location, paymethod, tag, feature
			$arrToHighlight = array
				(
				//hard code here, need to be modified later
				'shop_name' => $row['shop_name'],
				'nick' => $row['nick'],
				'created' => $row['created'],
				'location' => $row['location'],
				'description' => $row['description'],
				'paymethod' => $row['paymethod'],
				'feature' => $row['feature'],
				'tag' => $row['tag'],
			);
			$row = array_merge( $row, $shopSearch->BuildHighLight( $keyword, $arrToHighlight ) );

			//process tag information
			if( is_array( $row['tag']) && count($row['tag']) > 0 )
			{
				$row['tags'] = array();
				//replace the tag highlight
				foreach( $row['tags_plain'] as $strtag ){
					if( !empty( $tag ) && strpos( $strtag, $tag ) !== false){
						$row['tags'][] = str_replace( $tag, "<span class=\"hilight\">".$tag."</span>", $strtag );	
					}
					else{
						$row['tags'][] = $strtag;
					}	
				}
			}

			$highLighRes[] = $row;
		}

		$pageVars['dbRes'] = $highLighRes;
		
		$dbGroupByResWithCount = array();
		if( !edp_is_empty_string( $keyword ) ){
			//get category information
			$categoryGroupByArray = $shopSearch->GroupByQuery( $keyword, "cate_id_list" );
			$shoptCateDAO = new ShopCategoryDAO();
			$dbGroupByRes = $shoptCateDAO->GetShopCateInfoByIdList( array_keys( $categoryGroupByArray['matches'] ) );

			foreach( $dbGroupByRes as $item ) {
				$item['count'] = $categoryGroupByArray['matches'][$item['id']]['count'];
				$dbGroupByResWithCount[] = $item;
			}
		}
		$pageVars['dbGroupByRes'] = $dbGroupByResWithCount;

		//prepare page bar
		//reset sortby's value
		if( isset( $pageVars['sortby'] ) )
			$sortby = $pageVars['sortby'];

		$currentURL = htmlspecialchars( $_SERVER["REQUEST_URI"] );
		$currentURL = preg_replace( '/&p=[0-9]+/', "", $currentURL );
		$pageObj = new Pager( $currentURL, $pageVars['result']['total'], SHOP_INFO_PER_PAGE, $page, UP_RESULT_PAGE );
		$pageVars['pagebar'] = $pageObj->getBar();
	}

	//at last insert search history
	$searchDao = GetSearchDAO();
	$param = array( 'user_ip' => $_SERVER['SERVER_ADDR'], 'keyword' => $pageVars['keyword'] );
	$searchDao->AddSearchHistory( $param );
}
?>
